import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_pickers/pickers.dart';
import 'package:flutter_pickers/time_picker/model/date_mode.dart';
import 'package:flutter_pickers/time_picker/model/pduration.dart';
import 'package:get/get.dart';
import 'package:ty_smart_watch/ble/ble_util.dart';
import 'package:ty_smart_watch/ble/protocol_data_util.dart';
import 'package:ty_smart_watch/common/function_id.dart';
import 'package:ty_smart_watch/page/watch_setting_page/controller/watch_setting_controller.dart';
import 'package:ty_smart_watch/utils/Log.dart';

class WatchStepTargetPage extends StatefulWidget {
  const WatchStepTargetPage({super.key});

  @override
  State<WatchStepTargetPage> createState() => _WatchStepTargetPageState();
}

class _WatchStepTargetPageState extends State<WatchStepTargetPage> {
  int _functionId = 0; //功能id
  String _mac = ""; //设备地址

  final _trailingStyle = const TextStyle(color: Color(0xFF3075E9));
  final _titleStyle = const TextStyle(fontSize: 18);
  final _confirmColor = const Color(0xFF3075E9);
  final _unConfirmColor = const Color(0xFF80A3DF);

  final _controller = Get.put(WatchSettingController());

  @override
  void initState() {
    super.initState();
    _functionId = Get.arguments["id"];
    _mac = Get.arguments["mac"];
    Log.d("页面收到的数据：$_functionId > $_mac");
    _controller.getBleData(_mac, _functionId);
  }

  @override
  Widget build(BuildContext context) {
    ever(
      _controller.needClosePage,
      (need) => {
        Log.d("need close page: $need"),
        if (need == 2) {Get.back()}
      },
    );
    return Scaffold(
        appBar: AppBar(
          title: const Text("计步目标"),
          centerTitle: true,
          leading: IconButton(
            icon: const Icon(Icons.arrow_back_ios),
            onPressed: () {
              Get.back();
            },
          ),
        ),
        body: Column(
          children: [
            ListTile(
              title: Text("计步目标", style: _titleStyle),
              subtitle: const Text(
                "设置每日目标步数", /*style: _titleStyle*/
              ),
              trailing: Obx(
                () => Text(
                  "${_controller.stepTargetBean.value.stepTarget}步",
                  style: _trailingStyle,
                ),
              ),
              onTap: () {
                _clickStepTarget(_controller.stepTargetBean.value.stepTarget);
              },
            ),

            //占位
            const Expanded(child: SizedBox()),
            //确认按钮
            Container(
              width: double.infinity,
              height: 46,
              margin: const EdgeInsets.symmetric(horizontal: 20),
              child: TextButton(
                onPressed: () {
                  _confirm();
                },
                style: ButtonStyle(
                  backgroundColor: MaterialStateProperty.all(Colors.blue),
                  foregroundColor: MaterialStateProperty.all(Colors.white),
                  shape: MaterialStateProperty.all(
                    const RoundedRectangleBorder(
                      borderRadius: BorderRadius.all(Radius.circular(30)),
                    ),
                  ),
                ),
                child: const Text('确认'),
              ),
            ),
            const SizedBox(height: 60),
          ],
        ));
  }

  _clickStepTarget(int target) {
    TextEditingController textController = TextEditingController();
    Get.defaultDialog(
      title: '计步目标',
      content: Column(
        children: [
          Text("当前目标：$target步"),
          TextField(
            controller: textController,
            onChanged: (v) {},
            decoration: const InputDecoration(
                hintText: "请输入新目标(步)",
                hintStyle: TextStyle(
                  color: Color(0xFF969696),
                ),
                border: InputBorder.none),
            keyboardType: TextInputType.number,
            inputFormatters: [
              FilteringTextInputFormatter.digitsOnly, //数字，只能是整数
            ],
            maxLines: 1,
          ),
        ],
      ),
      textConfirm: '确定',
      textCancel: '取消',
      onConfirm: () {
        // 用户点击确认按钮时执行的操作
        if (textController.text.isNotEmpty) {
          int mDuration = int.parse(textController.text);
          var temp = _controller.stepTargetBean.value;
          temp.stepTarget = mDuration;
          _controller.updateStepTargetBean(temp);
        }
        Get.back();
      },
      onCancel: () {
        // 用户点击取消按钮时执行的操作
      },
    );
  }

  /// 提交信息到手表
  _confirm() {
    //将数据传送给手表 write
    _controller.updateNeedClosePage(1);
    var mData = _makeDataForWatch();
    BleUtil.writeBleData(_mac, BleUtil.makeWriteData(functionId: _functionId, data: mData));
  }

  ///整合要提交的数据
  List<int> _makeDataForWatch() {
    var temp = _controller.stepTargetBean.value;
    List<int> result = ProtocolDataUtil.instance!.stepTarget(temp.stepTarget);
    return result;
  }
}
